"""
des: 
author: 邵宁
date: 2022-08-17
"""
import os
import logging
import time

from flask import Flask, request
from flask_cors import CORS
from util import path, msg_manage, get_repo_info
from util import get_single_package_source_info
import session_manage
from server_rpm_agent_config import config

sess_man = session_manage.SessionListManage()
msg_man = msg_manage.MsgQueue()
logging.basicConfig(level=logging.INFO, format='[%(asctime)s] %(message)s', datefmt='%Y/%m/%d %H:%M:%S')
app = Flask(__name__)


@app.route("/get_all_tag", methods=['POST'])
def get_all_tags():
    return {
        "data": []
    }


@app.route("/get_all_arch", methods=['POST'])
def get_all_arch():
    return {
        "data": []
    }


@app.route("/search_rpm_name", methods=['POST'])
def search_rpm_name():
    rpm_name = request.json.get('rpm_name', '')
    # print("rpm_name", rpm_name)
    repo_info_map = get_repo_info.repo_info_map_load()
    rpm_info = get_repo_info.search_rpm_version(rpm_name, repo_info_map)
    link_repo_map = get_repo_info.get_link_repo_map()
    rpm_info_data = [{"tag_arch": k, "rpm_src_list": v, "repo_link": link_repo_map.get(k)} for k, v in rpm_info.items()]

    return {
        "status": 200,
        "data": rpm_info_data
    }


# @app.route('/rpmbuild_bs_by_tar_gz', methods=['POST'])
# def rpmbuild_bs_by_tar_gz():
#     print("接收文件")
#     file_metas = request.files.get('file', None)
#     host = request.form.get('host', '')
#     username = request.form.get('username', '')
#     password = request.form.get('password', '')
#     script_package_dir2rpm = request.form.get('script_package_dir2rpm', '')
#     # msg_preview_json = request.json.get('msg_preview', '')
#     ssh_res = ""
#     package_file_get = False
#     local_file_path = ""
#     if file_metas:  # 上传的是文件，通过request接受
#         filename = file_metas.filename
#         filepath = "static/file_save/rpmbuild.tar.gz"
#         path.dir_init(filepath)  # 初始化目录
#         file_metas.save(filepath)
#         ssh = ssh2server.ConnectSSH(host, username, password)
#         ssh.connect()
#         ssh.file_put("static/file_save/rpmbuild.tar.gz", "/root/rpmbuild.tar.gz")
#         for cmd_str in script_package_dir2rpm.split('\n'):
#             ssh_res += ">>> " + cmd_str + '\n' + ssh.exec(cmd_str.rstrip('\r')) + '\n'
#             if package_file_get:
#                 continue
#             ssh_ls_str = ssh.exec("ls -1 /root/rpmbuild/SRPMS |awk '{print i$0}' i='/root/rpmbuild/SRPMS/'",
#                                   is_show=True)
#             r = re.search(".*\.src\.rpm", ssh_ls_str)
#             if r:
#                 print("########>>>", r.group())
#                 save_dir = os.path.join("static/temp_package_file_save", path.get_file_name_random())
#                 path.dir_init(os.path.join(save_dir, "aa"))
#                 local_file_path = ssh.file_get(r.group(), save_dir)
#                 package_file_get = True
#         if package_file_get:
#             return {"status": 200, "msg": f"文件打包完成！", "log": ssh_res,
#                     "data": {"file_link": local_file_path, "file_name": os.path.basename(local_file_path)}}
#     return {"status": 801, "msg": f"文件打包失败！", "log": ssh_res,
#             "data": {"file_link": "", "file_name": ""}}

@app.route('/get_msg4task', methods=['POST'])
def get_msg4task():
    task_id = request.json.get('task_id', '')
    msg_obj_list = msg_man.pop_batch(task_id)
    sess_wait_idx = sess_man.get_index_of_wait_queue(task_id)
    if sess_wait_idx >= 0:
        msg_obj_list = [{
            "msg_id": 0,
            "msg_type": "msg",
            "timestamp": path.get_time_stamp(),
            "status_is_end": False,
            "msg": f"任务正在等待中，当前位置：{sess_wait_idx + 1}/{len(sess_man.thread_list_waiting)}"
        }]
    return {"status": 200, "msg": f"成功接收数据！", "data": msg_obj_list}


@app.route('/rpmbuild_bs_by_tar_gz', methods=['GET', 'POST'])
def rpmbuild_bs_by_tar_gz():
    print("正在接收文件")
    file_metas = request.files.get('file', None)
    para = {
        "host": request.form.get('host', ''),
        "username": request.form.get('username', ''),
        "password": request.form.get('password', ''),
        "script_package_dir2rpm": request.form.get('script_package_dir2rpm', ''),
    }

    ssh_res = ""
    if file_metas:  # 上传的是文件，通过request接受
        filepath = f"static/file_save/{path.get_file_name_random()}_rpmbuild.tar.gz"
        path.dir_init(filepath)  # 初始化目录
        file_metas.save(filepath)
        task_id = path.get_file_name_random()
        sess = session_manage.SessionPackage2Rpm(session_token=task_id, msg_man=msg_man, filepath=filepath,
                                                 mutex="package2rpm", **para)
        sess_man.join(sess)
        return {"status": 200, "msg": "文件已上传，打包任务已建立！", "data": {"task_id": task_id}}
    return {"status": 801, "msg": f"打包任务建立失败！", "log": ssh_res, "data": {"file_link": "", "file_name": ""}}


@app.route("/get_single_package_source_list", methods=['POST'])
def get_single_package_source_list():
    rpm_name = request.json.get('rpm_name', "")
    date_str = request.json.get('date', "")
    if rpm_name == "":
        rpm_name = '*'
    if date_str in ["", "None", None]:
        date_str = time.strftime("%Y%m%d")
    print("search single package", rpm_name, date_str)
    temp_file_path = "/tmp/temp4rpm_single_package_parse"
    repo_info_map = get_single_package_source_info.get_repo_data(base_url="http://172.30.12.115/pkg/",
                                                                 date_str=date_str,
                                                                 save_path=temp_file_path)
    get_single_package_source_info.repo_info_map_save(repo_info_map, save_path=os.path.join(temp_file_path, "dir_map"))
    repo_info_map = get_single_package_source_info.repo_info_map_load(save_path=os.path.join(temp_file_path, "dir_map"))
    single_package_source_info_data = get_single_package_source_info.search_rpm_version(rpm_name, repo_info_map)
    return {
        "status": 200,
        "data": single_package_source_info_data
    }


@app.route("/get_email_format", methods=['POST'])
def get_email_format():
    rpm_name = request.json.get('rpm_name', "")
    date_str = request.json.get('date', "")
    if rpm_name == "":
        rpm_name = '*'
    if date_str in ["", "None", None]:
        date_str = time.strftime("%Y%m%d")
    print("get single package email", rpm_name, date_str)
    temp_file_path = "/tmp/temp4rpm_single_package_parse"
    repo_info_map = get_single_package_source_info.repo_info_map_load(save_path=os.path.join(temp_file_path, "dir_map"))
    single_package_source_info_data = get_single_package_source_info.search_rpm_version(rpm_name, repo_info_map)
    str_email = get_single_package_source_info.get_email(single_package_source_info_data, date_str)
    return {
        "status": 200,
        "data": str_email
    }


@app.route("/api_compatibility_report_generate", methods=['POST'])
def api_compatibility_report_generate():
    koji_link = request.json.get('koji_link', "")
    task_id = path.get_file_name_random()
    sess = session_manage.SessionCompatibilityReportGenerate(session_token=task_id, msg_man=msg_man,
                                                             koji_link=koji_link,
                                                             **config.get("compatibility_report_generate", {}),
                                                             mutex="compatibility_report_generate")
    sess_man.join(sess)
    return {"status": 200, "msg": "兼容性报告生成任务已建立！", "data": {"task_id": task_id}}


CORS(app, resources=r'/*')
if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0', port=8081)  # 运行app
